package cn.gok.shiro.Test;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.subject.Subject;

/**
 * @Author: LKSV
 * @Description:
 * @Date:Created in 20:32 2021/8/16
 */
public class Test01 {
    public static void main(String[] args) {
        //创建securityManager
        DefaultSecurityManager defaultSecurityManager = new DefaultSecurityManager();

//        defaultSecurityManager.setRealm(new IniRealm("classpath:shiro.ini"));
        SimpleAccountRealm simpleAccountRealm = new SimpleAccountRealm();

        //设置md5加密
        HashedCredentialsMatcher credentialsMatcher = new HashedCredentialsMatcher();
        credentialsMatcher.setHashAlgorithmName("MD5");
        credentialsMatcher.setHashIterations(1024);//设置散列次数

        simpleAccountRealm.setCredentialsMatcher(credentialsMatcher);
        defaultSecurityManager.setRealm(simpleAccountRealm);
        //将安装工具类中设置默认安全管理器
        SecurityUtils.setSecurityManager(defaultSecurityManager);

        //获取主体对象
        Subject subject = SecurityUtils.getSubject();

        //创建token令牌
        UsernamePasswordToken token = new UsernamePasswordToken("sir", "123");

        try {
            subject.login(token);//用户登录
            System.out.println("登录成功~~");
        } catch (UnknownAccountException e) {
            e.printStackTrace();
            System.out.println("用户名错误!!");
        }catch (IncorrectCredentialsException e){
            e.printStackTrace();
            System.out.println("密码错误!!!");
        }

        if (subject.isAuthenticated()){
            boolean admin = subject.hasRole("user");
            System.out.println(admin);

            boolean permitted = subject.isPermitted("user:update");
            System.out.println(permitted);
        }
    }
}
